<?php
/**
 * @author css3 <css3@qq.com>
 */

namespace zonday\weixin\api;

use yii\helpers\FileHelper;
use zonday\weixin\Weixin;

class Media extends Api
{
    /**
     * 上传临时素材 Curl方式
     *
     * @see http://mp.weixin.qq.com/wiki/5/963fc70b80dc75483a271298a76a8d59.html
     * @param string $type
     * @param string $mediaPath 文件路径
     * @param string $mediaName 文件名
     * @return mixed
     */
    public function upload($type, $mediaPath, $mediaName = '')
    {
        $mediaName = $mediaName ? $mediaName : basename($mediaPath);
        if (function_exists('curl_file_create')) {
            $media = curl_file_create($mediaPath, FileHelper::getMimeType($mediaPath), $mediaName);
        } else {
            $media = '@' . $mediaPath;
        }
        return $this->request('media/upload', ['type' => $type], ['media' => $media], ['jsonEncode' => false]);
    }

    /**
     * 上传图文消息素材
     * @see http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html
     * @param array $post
     * @return mixed
     */
    public function uploadNews(array $post)
    {
        return $this->request('media/uploadnews', null, $post);
    }

    /**
     * 群发中的 视频 特殊处理
     * @see http://mp.weixin.qq.com/wiki/15/5380a4e6f02f2ffdc7981a8ed7a40753.html
     * @param string $mediaId
     * @param string $title
     * @param string $description
     * @return mixed
     */
    public function uploadVideo($mediaId, $title, $description)
    {
        return $this->request('https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo', null, ['media_id' => $mediaId, 'title' => $title, 'description' => $description]);
    }

    /**
     * 获取临时素材 Curl
     * @see http://mp.weixin.qq.com/wiki/11/07b6b76a6b6e8848e855a435d5e34a5f.html
     * @param string $mediaId
     * @return mixed
     */
    public function get($mediaId)
    {
        return $this->request('media/get', ['media_id' => $mediaId], null, ['raw' => true]);
    }

    /**
     * 下载素材url地址
     * @see http://mp.weixin.qq.com/wiki/11/07b6b76a6b6e8848e855a435d5e34a5f.html
     * @param string $mediaId
     * @return string
     */
    public function downloadUrl($mediaId)
    {
        return Weixin::API_BASE_URL . '/media/get?access_token=' . $this->getWeixin()->getAccessToken() . '&media_id=' . $mediaId;
    }

    /**
     * 表单上传url
     * @param $type
     * @return string
     */
    public function getFormUrl($type) {
        return Weixin::API_BASE_URL . '/media/upload?access_token=' . $this->getWeixin()->getAccessToken() . '&type=' . $type;
    }
}
